package com.fingard.dsp.bank.directbank.alipay01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IAcceptNotice;
import com.fingard.dsp.bank.directbank.cmb01.CMB01Base;
import com.fingard.generalobj.NoticeReq;
import com.fingard.generalobj.NoticeResp;
import com.fingard.net.listener.SocketReceiver;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.Map;

public class ALIPAY01AcceptNotice extends CMB01Base implements IAcceptNotice {

    @Override
    public NoticeResp dealNotice(NoticeReq pNtReq) throws Exception {
        NoticeResp resp = new NoticeResp();
        String p_reqs = pNtReq.getReqString();
        WriteBankLogLn("接收到请求：" + pNtReq.getFullString());

        PrintStream ps = null;
        String tmpFileName = FGBiz.DSPHOME_Parent + File.separator + "signnotify";
        try {
            if (p_reqs.length() == 0) {
                String tmpStrRet = "空报文";
                WriteBankLogLn("响应：" + tmpStrRet);
                resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
                return resp;
            }


            File dir1 = new File(tmpFileName);
            if (!dir1.exists()) {
                dir1.mkdir();
            }

            Date a = new Date();
            File tmpFile1 = new File(tmpFileName + File.separator + Format.DateTime14Format.format(a) + ".txt");
            if (!tmpFile1.exists()) {
                tmpFile1.createNewFile();
                ps = new PrintStream(new FileOutputStream(tmpFile1));
                ps.println(p_reqs);
                ps.close();
            }

            String p_req = "";
            if (p_reqs.contains("\n\n")) {
                //通过空白行截取字符串
                int index1 = p_reqs.indexOf("\n\n");
                p_req = p_reqs.substring(index1 + 2);
            } else {
                p_req = p_reqs;
            }

            WriteBankLogLn("支付宝批量付款通知报文：" + p_req);

            //写入文件的字符串
            StringBuilder reader_str = new StringBuilder();
            Map params = convertToMap(p_req);

            if (params != null) {
                boolean verify = true;
                if (verify) {
                    String[] sucDetails = params.get("success_details").toString().split("\\|");
                    String[] falDetails = params.get("fail_details").toString().split("\\|");
                    String[] detail = new String[sucDetails.length + falDetails.length -2];
                    /**
                     * 执行数组拷贝
                     * System.arraycopy(源数组，源数组的起始位置，目标数组，目标数组的起始位置，拷贝多少位)
                     */
                    System.arraycopy(sucDetails, 0, detail,0, sucDetails.length-1);
                    System.arraycopy(falDetails, 0, detail, sucDetails.length, falDetails.length-1);
                    //签约、解约成功
                    reader_str.append("<ATSYH><TransResp><BankCode>ALIPAY01</BankCode>");
                    reader_str.append("<TransType>1998</TransType>");
                    reader_str.append("<TransSeqID></TransSeqID>");
                    reader_str.append("<TransParam><ReqSeqID>" + params.get("batch_no").toString() + "</ReqSeqID>");
                    reader_str.append("<RespCode></RespCode>");
                    reader_str.append("<RespInfo></RespInfo>");
                    reader_str.append("<TransState></TransState>");
                    reader_str.append("<PayInfoCode></PayInfoCode>");
                    String pay_act = params.get("pay_account_no").toString();
                    for (int i = 0; i < detail.length; i++) {
                        /**
                         * 转账成功:流水号^收款方账号^收款账号姓名^付款金额^成功标识(S)^成功原因(null)^支付宝内部流水号^完成时间
                         *           0       1          2         3        4           5               6           7
                         * 转账失败:流水号^收款方账号^收款账号姓名^付款金额^失败标识(F)^失败原因^支付宝内部流水号^完成时间
                         */
                        String[] eachdetail = detail[i].split("^");
                        reader_str.append("<DetailRecord>");
                        reader_str.append("<PostScript>" + eachdetail[0] + "</PostScript>");
                        reader_str.append("<RecAct>" + eachdetail[1] + "</RecAct>");
                        reader_str.append("<RecName>" + eachdetail[2] + "</RecName>");
                        reader_str.append("<PayAmount>" + eachdetail[3] + "</PayAmount>");
                        reader_str.append("<Result>" + eachdetail[4] + "</Result>");
                        reader_str.append("<PayInfoCode>" + eachdetail[4] + "</PayInfoCode>");
                        reader_str.append("<Memo>" + eachdetail[5] + "</Memo>");
                        reader_str.append("</DetailRecord>");
                    }
                    reader_str.append("</TransParam></TransResp></ATSYH>");

                    File dir = new File(tmpFileName);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    File tmpFile = new File(tmpFileName + File.separator + pay_act + ".txt");
                    if (!tmpFile.exists()) {
                        tmpFile.createNewFile();
                        ps = new PrintStream(new FileOutputStream(tmpFile));
                        ps.println(reader_str);
                        ps.close();
                    }
                }
            } else {
                String tmpStrRet = "报文格式错误";
                WriteBankLogLn("响应：" + tmpStrRet);
                resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
                return resp;
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        } finally {
            if (ps != null) {
                ps.close();
            }
        }
        String tmpStrRet = "";
        WriteBankLogLn("响应：" + tmpStrRet);
        resp.respBytes = tmpStrRet.getBytes(pNtReq.reqCharset);
        return resp;
    }

    @Override
    public void getContentLength(SocketReceiver p_receiver) throws Exception {

    }
}
